package com.feri.fc.caregiver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feri.fc.caregiver.service.PhysicianService;
import com.feri.fc.config.RedisKeyConfig;
import com.feri.fc.config.RocketMQConfig;
import com.feri.fc.dao.PhysicianDao;
import com.feri.fc.dao.PhysicianLogDao;
import com.feri.fc.entity.Physician;
import com.feri.fc.entity.PhysicianLog;
import com.feri.fc.ocr.BaiduOcrUtil;
import com.feri.fc.ocr.IdCard;
import com.feri.fc.param.PhysicianAdd;
import com.feri.fc.pay.alipay.AliPayUtil;
import com.feri.fc.pay.util.PayUtil;
import com.feri.fc.type.PhysicianStatus;
import com.feri.fc.vo.R;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/26 10:20
 * @Modified:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PhysicianServiceImpl implements PhysicianService {
    private final PhysicianDao dao;
    private final PhysicianLogDao logDao;
    private final RocketMQTemplate rocketMQTemplate;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public R add(PhysicianAdd add, Integer uid) {
        //1.查询 验证 本次是否可以申请
        LambdaQueryWrapper<Physician> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Physician::getUid,uid).or().eq(Physician::getPhone,add.getPhone());
        wrapper.last(" limit 1");
        Physician physician=dao.selectOne(wrapper);
        if(physician!=null){
            return R.fail("亲，已认证过陪诊师，请检查！");
        }
        //2.创建对象 操作数据库
        physician=new Physician(uid);
        //对象内容的拷贝 多种方式  性能排序
        BeanUtils.copyProperties(add,physician);

        dao.insert(physician);
        //记录日志
        logDao.insert(new PhysicianLog(physician.getId(), physician.getStatus(), "申请成为陪诊师"));
        //发送MQ  异步 对身份证、健康证 审核识别
        rocketMQTemplate.convertAndSend(RocketMQConfig.TOPIC_REAL,physician.getId());


        return R.ok();
    }

    @Override
    public boolean audit(Integer id) {
        //1.查询
        Physician physician=dao.selectById(id);
        if(physician==null){
            return false;
        }
        //2.识别 身份证 健康证
        if(!stringRedisTemplate.hasKey(RedisKeyConfig.TOKEN_BAIDU)){
            String json=BaiduOcrUtil.authToken();
            JSONObject jo=new JSONObject(json);
            stringRedisTemplate.opsForValue().set(RedisKeyConfig.TOKEN_BAIDU,jo.getStr("access_token"),
                    jo.getLong("expires_in"), TimeUnit.SECONDS);
        }
        String token=stringRedisTemplate.opsForValue().get(RedisKeyConfig.TOKEN_BAIDU);
//        String token="24.e230dbda52417e145f2c1adc9ffccd16.2592000.1735198801.282335-17540802";
        IdCard card= BaiduOcrUtil.ocrIdCardFront(token,physician.getCardFront());

        //3.比较 验证身份证和健康证一个人
        if(card!=null){
            String health=BaiduOcrUtil.ocrImg(token,physician.getHealthCard());
            log.info("健康证识别={}",health);
            //            if(StringUtils.hasLength(health)){
//                JSONObject jo=new JSONObject(health);
//                if(jo.getInt("words_result_num")>0){
//                    JSONArray ja=jo.getJSONArray("words_result");
//
//                }
//            }
        }
        //4.更新结果 审核通过  审核拒绝
        if(card!=null && StringUtils.hasLength(card.getCardNo())){
            //通过
            BeanUtils.copyProperties(card,physician);
            physician.setUpdateTime(new Date());
            physician.setStatus(PhysicianStatus.审核通过.getValue());
        }else{
            //拒绝
            physician.setStatus(PhysicianStatus.审核拒绝.getValue());
            physician.setUpdateTime(new Date());
        }
        dao.updateById(physician);
        logDao.insert(new PhysicianLog(physician.getId(), physician.getStatus(), "对身份证和健康证进行审核处理"));

        return true;
    }

    @Override
    public R createPay(Integer id) {
        //1.查询 验证
        Physician physician=dao.selectById(id);
        if(!physician.getStatus().equals(PhysicianStatus.审核通过.getValue())){
            return R.fail("请检查状态，不允许押金缴纳！");
        }
        //2.根据 支付方式  创建对应的支付信息

        String result= AliPayUtil.createPay("p"+id+"-"+System.currentTimeMillis(),"缴纳押金",500.0);
        log.info("支付宝支付创建={}",result);

        if(StringUtils.hasLength(result)){
            //记录 支付日志

            //记录 状态日志
            physician.setStatus(PhysicianStatus.未缴纳.getValue());
            physician.setUpdateTime(new Date());
            dao.updateById(physician);
            logDao.insert(new PhysicianLog(physician.getId(), physician.getStatus(), "创建了支付，等待付款"));

            return R.ok(result);
        }
        return R.fail();
    }
    @Transactional //事务
    @Override
    public boolean updatePay(String no, String status) {
        //1.根据订单号 获取陪诊人ID
        if(no.indexOf("-")<=0){
            return false;
        }
        String id=no.substring(1,no.indexOf("-"));
        Physician physician=dao.selectById(id);
        String s= PayUtil.getPayStatus(status);
        if(s.equals("支付完成")){
            physician.setStatus(PhysicianStatus.未学习.getValue());
            physician.setScore(500);
            //记录 支付日志  支付成功
        }else {
            physician.setStatus(PhysicianStatus.支付失败.getValue());
            //记录 支付日志  支付成功

        }
        physician.setUpdateTime(new Date());
        dao.updateById(physician);
        //记录
        logDao.insert(new PhysicianLog(physician.getId(), physician.getStatus(),"支付状态发生了改变"));

        return true;
    }

    @Override
    public R all() {
        return R.ok(dao.selectList(null));
    }

}
